package services

import (
	"blog-server/app/common/request"
	"blog-server/app/models"
	"blog-server/global"
	"blog-server/utils"
	"errors"
	"fmt"
	"strconv"
)

type adminService struct {
}

var AdminService = new(adminService)

// AdminRegister 注册
func (adminServices *adminService) AdminRegister(params request.Register) (err error, user *models.AdminUser) {
	var result = global.App.DB.Where("phone_num = ?", params.PhoneNum).Select("user_id").First(&models.AdminUser{})
	fmt.Print(result)
	if result.RowsAffected != 0 {
		err = errors.New("该手机号已注册")
		return
	} else {
		user = &models.AdminUser{
			UserName: params.UserName,
			Password: utils.BcryptMake([]byte(params.Password)),
			PhoneNum: params.PhoneNum,
		}
		err = global.App.DB.Create(&user).Error
		return
	}
}

func (adminServices *adminService) AdminLogin(params request.Login) (err error, user *models.AdminUser) {
	err = global.App.DB.Where("phone_num", params.PhoneNum).First(&user).Error
	fmt.Print(err)
	if err != nil || !utils.BcryptMakeCheck([]byte(params.Password), user.Password) {
		err = errors.New("用户名或密码错误")
		return
	} else {
		return
	}
}

func (adminServices *adminService) GetUserInfo(userId string) (err error, user models.AdminUser) {
	intId, err := strconv.Atoi(userId)
	err = global.App.DB.First(&user, intId).Error
	if err != nil {
		err = errors.New("数据不存在")
	}
	return
}
